﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace VM.Common.Request
{
    public class HttpHelper
    {


        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="Url"></param> 
        /// <param name="AuthType">验证类型   这里示例两种  一种是cookie   一种是Bear </param>
        /// <param name="token"></param>
        /// <param name="httpClient">这里是注入的方式   也可以不用注入  直接new</param>
        /// <returns></returns>
        public static async Task<dynamic> DoGetRequestAsync(string url, string AuthType, string token)
        {
            try
            {
                using(HttpClient client = new HttpClient()) //非注入方式
                //using (var client = httpClient.CreateClient())
                {
                    //使用注入的httpclientfactory获取client 
                    client.BaseAddress = new Uri(url);
                    if (!string.IsNullOrWhiteSpace(AuthType))
                    {
                        switch (AuthType)
                        {
                            //Bearer认证      如果接口未加密省略此行
                            case "Bearer": client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); break;
                            case "Cookie": client.DefaultRequestHeaders.Add("Cookie", token); break;

                        }
                    }
                    //设置请求体中的内容，并以gost的方式请求
                    var response = await client.GetAsync(url);
                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return result;
                    }
                    return new { ok = false, msg = "请求异常", data = "" };
                }
            }
            catch (Exception e)
            {
                return new { ok = false, msg = e.Message, data = "" };
            }
        }
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="parameter">序列化之后的json</param>
        /// <param name="ContentType">例如："application/json"</param>
        /// <param name="Auth">验证类型   这里示例两种  一种是cookie   一种是Bear </param>
        /// <param name="token"></param>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static async Task<dynamic> DoPostRequest(string Url, string parameter, string ContentType, string AuthType, string token)
        {
            try
            {
                using(HttpClient client = new HttpClient()) //非注入方式
                //using (var client = httpClient.CreateClient())
                {
                    string responseBody = string.Empty;
                    client.DefaultRequestHeaders.Add("Method", "Post");
                    var content = new StringContent(parameter, Encoding.UTF8, ContentType);
                    if (!string.IsNullOrEmpty(AuthType))
                    {
                        switch (AuthType)
                        {
                            //Bearer认证      如果接口未加密省略此行
                            case "Bearer": client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); break;
                            case "Cookie": client.DefaultRequestHeaders.Add("Cookie", token); break;

                        }

                        //var authorizationBased64 = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{userName}:{password}"));//basic认证方式   用户名:密码 然后base64加密
                        //client.DefaultRequestHeaders.Add("Authorization", authorizationBased64);
                    }
                    HttpResponseMessage response = await client.PostAsync(Url, content);
                    //response.EnsureSuccessStatusCode();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        responseBody = response.Content.ReadAsStringAsync().Result;
                        dynamic res = JsonConvert.DeserializeObject<dynamic>(responseBody);
                        string CookieValue = "";
                        if (AuthType == "Cookie" && Url.EndsWith("login"))
                        {
                            //如果认证是cookie那么要从请求头获取cookie  调用其它接口时要在塞到cookie里
                            string[] Cookie = (string[])response.Headers.GetValues("Set-Cookie");
                            CookieValue = Cookie[0].Split(';')[0];
                        }
                        return new { ok = true, isTryException = false, cookie = CookieValue, data = res };
                    }
                    else
                    {
                        responseBody = response.Content.ReadAsStringAsync().Result;

                        return new { ok = false, isTryException = false, cookie = "", data = responseBody };
                    }
                }
            }
            catch (Exception e)
            {
                return new { ok = false, isTryException = true, msg = e.Message, data = "" };
            }
        }


        public static string  PostRequest(string Url, string parameter, string ContentType, Encoding encoding =null)
        {
            try
            {
                using (HttpClient client = new HttpClient()) //非注入方式
                //using (var client = httpClient.CreateClient())
                {
                    string responseBody = string.Empty;
                    client.DefaultRequestHeaders.Add("Method", "Post");
                    var content = new StringContent(parameter, Encoding.UTF8, ContentType);
                    
                    var  response =  client.PostAsync(Url, content);
                    response.Wait();
                    var t2 = response.Result.Content.ReadAsByteArrayAsync();
                    return encoding.GetString(t2.Result);
                    ////response.EnsureSuccessStatusCode();
                    //if (response.StatusCode == HttpStatusCode.OK)
                    //{
                    //    responseBody = response.Content.ReadAsStringAsync().Result;
                    //    dynamic res = JsonConvert.DeserializeObject<dynamic>(responseBody);
                    //    string CookieValue = "";

                    //    return new { ok = true, isTryException = false, cookie = CookieValue, data = res };
                    //}
                    //else
                    //{
                    //    responseBody = response.Content.ReadAsStringAsync().Result;

                    //    return   responseBody.ToString() ;
                    //}
                }
            }
            catch (Exception e)
            {
                return  "" ;
            }
        }


        /// <summary>
        /// post请求      ContentType", "application/x-www-form-urlencoded
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="parameter"></param>
        /// <param name="ContentType"></param>
        /// <param name="token"></param>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static async Task<dynamic> DoPostRequest(string Url, Dictionary<string, string> parameter, string token)
        {
            try
            {
                using(HttpClient client = new HttpClient()) //非注入方式
                //using (var client = httpClient.CreateClient())
                {
                    string responseBody = string.Empty;
                    client.DefaultRequestHeaders.Add("Method", "Post");
                    var content = new FormUrlEncodedContent(parameter);
                    if (!string.IsNullOrEmpty(token))
                    {
                        client.DefaultRequestHeaders.Add("Authorization", "Bearea " + token); //Bearea认证      如果接口未加密省略此行

                        //var authorizationBased64 = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{userName}:{password}"));//basic认证方式   用户名:密码 然后base64加密
                        //client.DefaultRequestHeaders.Add("Authorization", authorizationBased64);
                    }
                    content.Headers.Add("ContentType", "application/x-www-form-urlencoded");
                    HttpResponseMessage response = await client.PostAsync(Url, content);
                    response.EnsureSuccessStatusCode();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        responseBody = response.Content.ReadAsStringAsync().Result;
                        dynamic res = JsonConvert.DeserializeObject<dynamic>(responseBody);

                        return new { ok = true, data = res };
                    }
                    return new { ok = false, msg = "请求异常", data = "" };
                }
            }
            catch (Exception e)
            {
                return new { ok = false, msg = e.Message, data = "" };
            }
        }
    }
}
